package com.panopset.swing;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.HierarchyBoundsAdapter;
import java.awt.event.HierarchyEvent;

import com.panopset.gui.TPanel;

/**
 * Resizable Osgw panel.
 *
 * @author Karl Dinwiddie
 *
 */
public abstract class OsgwResizable {

    public OsgwResizable() {
        getPanel().addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
            @Override
            public void ancestorResized(HierarchyEvent e) {
                update();
            }
        });
        update();
    }

    private Osgw osgw;

    public Osgw getOsgw() {
        if (osgw == null) {
            osgw = new Osgw(getPanel().getSize()) {

                @Override
                public void paintCycle(Graphics2D g) {
                    OsgwResizable.this.paintCycle(g);
                }

            };
        }
        return osgw;
    }
    /**
     *
     * @param g
     */
    public abstract void paintCycle(Graphics2D g);

    private Dimension boundParentSize;

    void update() {
        if (panel == null) {
            return;
        }
        if (panel.getSize().height == 0) {
            return;
        }
        if (panel.getSize().width == 0) {
            return;
        }
        if (boundParentSize != null && getPanel().getSize().equals(boundParentSize)) {
            return;
        }
        if (osgw != null) {
            osgw.stop();
        }
        panel.removeAll();
        osgw = null;
        panel.add(getOsgw().getPanel());
        boundParentSize = getPanel().getSize();
        getPanel().invalidate();
        App.app.f.getFrame().validate();
    }

    private TPanel panel;

    /**
     * @return Panel that contains the Osgw.
     */
    public TPanel getPanel() {
        if (panel == null) {
            panel = new TPanel(new GridLayout(1,1));
        }
        return panel;
    }
}
